#include "rel.h"

/**
 * Prints a specific number of bytes in a given buffer in hexadecimal
 * used for debugging
 * 
 * @param buffer - buffer to be printed
 * @param byteCount - number of bytes to print
 */

void printMessage(char * buffer, int byteCount) {

  // Cast buffer as unsigned char
  void * ptr = (void * ) buffer;
  unsigned char * bufferPtr = (unsigned char *) ptr; 
  
  int i;
  
  printf("\n");
  
  for (i = 0; i < byteCount; i++){
    printf("%x ", bufferPtr[i]);
  }
  printf("\n");
}

/**
 * Parse Data Message
 *
 * @param None
 *
 * @return An integer that represents the message size which is returned from 
 * one of the parsing functions.
 */
int parseMessage() {

  // Cast buffer as unsigned char
  void * ptr = (void * ) receiveMessageBuffer;
  unsigned char * bufferPtr = (unsigned char *) ptr;  

  if (bufferPtr[0] == 0xFF) {
    // Parse File Status Message
    if(debug)
    	puts("Received a file status message");
    return parseFileStatusMessage();
  }
  
  else if (bufferPtr[0] == 0xDD) {
    if(debug)
      puts("Received a data message");
    return parseDataMessage();
  }
  
  else if (bufferPtr[0] == 0xAA) {
    if(debug)
      puts("Received an ACK message");
    return parseAckMessage();
  }
  else {
  	puts("Received unknown message type. Aborting.");
  	return 0;
  }
}

/**
 * Tells us what kind of message is in a buffer
 *
 * @param buffer - where the message is stored
 * @return error code - 1 for error
 */
 
int messageType(char * buffer) {
  
  // Cast buffer as unsigned char
  void * ptr = (void * ) buffer;
  unsigned char * bufferPtr = (unsigned char *) ptr;  
  
  // Checks first byte to grab the message type
  if (bufferPtr[0] == 0xFF){
    if (debug){
      printf("\nFile Status Message\n");
    }
  }
  
  else if (bufferPtr[0] == 0xAA){
    if (debug){
      printf("\nACK Message\n");
    }  
  }
  
  else if (bufferPtr[0] == 0xDD){
    if (debug){
      printf("\nData Message\n");
    }
  }
  
  // Not a standard message type
  else {
    printf("\nNot a standard message.\n");
    return 1;
  }  
}